package cn.xd.itstack.springframework.beans.factory.support;

import cn.xd.itstack.springframework.beans.BeansException;
import cn.xd.itstack.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Classname SimpleInstantiationStrategy
 * @Description TODO
 * @Date 2022/5/11 下午4:56
 * @Created by lvxiaodong
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    /**
     * JDK 实现
     * @param beanDefinition
     * @param beanName
     * @param constructor  类信息，为了获取构造函数
     * @param args
     * @return
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object... args) {
        Class beanClass = beanDefinition.getBeanClass();
        Object bean;
        try {
            if(constructor!=null){
                return beanClass.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);

            }else {
                return beanClass.getConstructor().newInstance();
            }
        }catch (InstantiationException | IllegalAccessException | InvocationTargetException| NoSuchMethodException e){
            throw  new BeansException("Failed to instantiate "+beanClass.getName()+"]",e);
        }
    }
}
